<?php

if (!isset($website) ) { header('HTTP/1.1 404 Not Found'); die; }

//DELETE COMMENT - ADMIN
if (os_is_logged() AND isset($_SESSION["level"] ) AND $_SESSION["level"]>=9 AND isset($_GET["delete_comment"]) AND isset($_GET["post_id"]) ) {
   $id = safeEscape( (int) $_GET["delete_comment"] );
   $pid = safeEscape( (int) $_GET["post_id"] );
   
   $del = $db->query("DELETE FROM ".OSDB_COMMENTS." WHERE id = '".$id."' AND post_id = '".$pid."' LIMIT 1");
   $get = $db->query("SELECT COUNT(*) FROM ".OSDB_COMMENTS." WHERE post_id= '".$pid."' LIMIT 1");
   $r = $db->fetch_row($get);
   $TotalComments = $r[0];
   $update = $db->query("UPDATE ".OSDB_NEWS." SET ".OSDB_COMMENTS." = '".$TotalComments."' WHERE news_id = '".$pid."' ");
   
   header('location: '.OS_HOME.'?post_id='.$pid.'#comments'); die;
}

  if ( isset($_POST["add_comment"]) AND os_is_logged() AND isset($_GET["post_id"]) AND is_numeric($_GET["post_id"]) AND isset($_SESSION["code"]) AND isset($_POST["code"]) AND isset($_POST["pid"]) ) {
  
   require_once(OS_PLUGINS_DIR.'index.php');
   os_init();
  
  $id = safeEscape( (int) $_GET["post_id"]);
  $text = OS_StrToUTF8( $_POST["post_comment"] );
  $text =  (PrepareTextDB( $text ));
  //$text = EscapeStr( ($text) );
  //$text = (($text));
  $errors = "";
  
  //Check if comments is allowed for this post
  $check = $db->query("SELECT * FROM ".OSDB_NEWS." WHERE news_id = '".$id."' AND allow_comments = 1");
  if ( $db->num_rows($check)<=0 ) $errors.="<div>".$lang["error_comment_not_allowed"]."</div>";
  
  if ( $_SESSION["code"] != $_POST["code"])  $errors.="<div>".$lang["error_invalid_form"]."</div>";
  if ( $_POST["pid"] != $id )                $errors.="<div>".$lang["error_invalid_form"]."</div>";
  if ( strlen($text)<=3 )   $errors.="<div>".$lang["error_text_char"] ."</div>";
  
  
  if ( empty($errors) ) {
     $result = $db->query("INSERT INTO ".OSDB_COMMENTS."(user_id, page, post_id, text, date, user_ip) 
	 VALUES('".$_SESSION["user_id"]."', 'news', '".(int) $id."', '".$text."', '".time()."', '".$_SERVER["REMOTE_ADDR"]."')");
	 
	 $get = $db->query("SELECT COUNT(*) FROM ".OSDB_COMMENTS." WHERE post_id= '".$id."' LIMIT 1");
	 $r = $db->fetch_row($get);
     $TotalComments = $r[0];
	 $update = $db->query("UPDATE ".OSDB_NEWS." SET `comments` = '".$TotalComments."' WHERE news_id = '".$id."' ");
	 
	 if ( $result ) {
	    header("location: ".OS_HOME."?post_id=".$id."#comments"); die;
	 }
  }
  
  }
?>